package org.example.promptword.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;
import org.example.promptword.Vo.TagVO;
import org.example.promptword.Vo.TemplateVO;
import org.example.promptword.common.BaseException;
import org.example.promptword.dto.TemplateCreateRequest;
import org.example.promptword.dto.TemplateQueryRequest;
import org.example.promptword.service.PromptRelationTagService;
import org.springframework.util.StringUtils;
import org.example.promptword.common.ColorGenerator;
import org.example.promptword.entity.*;
import org.example.promptword.mapper.PromptTagMapper;
import org.example.promptword.mapper.PromptTemplateSquareMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class PromptTemplateSquareServiceImpl {
    @Autowired
    private PromptTemplateSquareMapper promptTemplateSquareMapper;
    @Autowired
    private PromptTagMapper promptTagMapper;
    @Autowired
    private ColorGenerator colorGenerator;
    @Autowired
    private PromptRelationTagService promptRelationTagService;

    public PageInfo<TemplateVO> getTemplates(TemplateQueryRequest queryRequest) {
        Page<PromptTemplateSquare> page = new Page<>(queryRequest.getPage(), queryRequest.getSize());
        // 调用新的Mapper方法，传递分页信息、搜索内容和标签列表
        List<PromptTemplateSquare> templates = promptTemplateSquareMapper.selectPageWithTagFilter(
                page,
                StringUtils.hasText(queryRequest.getContent()) ? queryRequest.getContent() : null,
                CollectionUtils.isNotEmpty(queryRequest.getTags()) ? queryRequest.getTags() : null
        );

        // 转换为VO并查询关联的标签
        List<TemplateVO> items = templates.stream().map(template -> {
            TemplateVO vo = new TemplateVO();
            vo.setTemplateId(template.getId());
            vo.setContent(template.getContent());
            vo.setType(template.getType());
            vo.setCreatedTime(template.getCreateTime().getTime());
            vo.setUpdatedTime(template.getUpdateTime().getTime());

            // 查询关联的标签
            List<TagVO> tags = promptTagMapper.findTagsByTemplateId(template.getId());
            tags.forEach(this::ensureAndUpdateTagColor);
            vo.setTags(tags);

            return vo;
        }).collect(Collectors.toList());

        // 将分页信息和VO列表封装到 PageInfo 中
        PageInfo<TemplateVO> pageInfo = new PageInfo<>(items);
        pageInfo.setTotal(page.getTotal());  // 总记录数
        pageInfo.setPageSize((int) page.getSize()); // 每页显示的数量
        pageInfo.setPageNum((int) page.getCurrent());  // 当前页码
        pageInfo.setPages((int) page.getPages()); // 获取总页数
        return pageInfo;
    }

    //统一的标签颜色处理方法
    private void ensureAndUpdateTagColor(TagVO tag) {
        if (tag.getColor() == null || tag.getColor().isEmpty() ||
                tag.getRgbColor() == null || tag.getRgbColor().isEmpty()) {
            ColorGenerator.ColorResult colors = colorGenerator.generateColorForTag(tag.getTagId());
            LambdaQueryWrapper<PromptTag> updateWrapper = new LambdaQueryWrapper<>();
            updateWrapper.eq(PromptTag::getId, tag.getTagId())
                         .isNull(PromptTag::getColor)
                         .or()
                         .isNull(PromptTag::getRgbColor);
            PromptTag updateTag = new PromptTag();
            updateTag.setColor(colors.getHexColor());
            updateTag.setRgbColor(colors.getRgbaColor());

            promptTagMapper.update(updateTag, updateWrapper);
            tag.setColor(colors.getHexColor());
            tag.setRgbColor(colors.getRgbaColor());
        }
    }

    public List<TagVO> getTags(String name) {
        LambdaQueryWrapper<PromptTag> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PromptTag::getDeleted, 0);

        if (StringUtils.hasText(name)) {
            wrapper.eq(PromptTag::getName, name);
        }

        return promptTagMapper.selectList(wrapper).stream().map(tag -> {
            TagVO vo = new TagVO();
            vo.setTagId(tag.getId());
            vo.setName(tag.getName());
            vo.setType(tag.getType());
            vo.setColor(tag.getColor());
            vo.setRgbColor(tag.getRgbColor());
            ensureAndUpdateTagColor(vo);
            return vo;
        }).collect(Collectors.toList());
    }


    @Transactional(rollbackFor = Exception.class)
    public Integer createTemplate(TemplateCreateRequest request) {
        // 1. 验证请求参数
        if (StringUtils.isEmpty(request.getContent())) {
            throw new BaseException("500","模板内容不能为空");
        }

        // 2. 验证标签是否存在
        if (CollectionUtils.isNotEmpty(request.getTagIds())) {
            // 查询有效的标签ID列表
            LambdaQueryWrapper<PromptTag> tagQueryWrapper = new LambdaQueryWrapper<>();
            tagQueryWrapper.eq(PromptTag::getDeleted, false)
                    .in(PromptTag::getId, request.getTagIds());
            List<Integer> existingTagIds = promptTagMapper.selectList(tagQueryWrapper).stream()
                    .map(PromptTag::getId).collect(Collectors.toList());
            List<Integer> invalidTagIds = request.getTagIds().stream()
                    .filter(tagId -> !existingTagIds.contains(tagId))
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(invalidTagIds)) {
                throw new BaseException("500","标签不存在或已删除: " + invalidTagIds);
            }
        }
        // 2.1 处理自定义标签
        List<Integer> newTagIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(request.getCustomTags())) {
            // 先检查是否有重复的标签名
            List<String> existingTagNames = new ArrayList<>();
            for (String customTagName : request.getCustomTags()) {
                LambdaQueryWrapper<PromptTag> tagQueryWrapper = new LambdaQueryWrapper<>();
                tagQueryWrapper.eq(PromptTag::getName, customTagName)
                        .eq(PromptTag::getDeleted, false);
                PromptTag existingTag = promptTagMapper.selectOne(tagQueryWrapper);
                if (existingTag != null) {
                    existingTagNames.add(customTagName);
                }
            }
            // 如果存在重复标签，抛出异常
            if (!existingTagNames.isEmpty()) {
                throw new BaseException("500","以下标签已存在，请直接选择: " + String.join(", ", existingTagNames));
            }

            // 创建新标签
            for (String customTagName : request.getCustomTags()) {
                // 创建新标签
                PromptTag newTag = new PromptTag();
                newTag.setName(customTagName);
                newTag.setCreateTime(new Date());
                newTag.setUpdateTime(new Date());
                newTag.setDeleted(false);

                // 先插入获取ID
                promptTagMapper.insert(newTag);

                // 为新标签生成颜色
                ColorGenerator.ColorResult colors = colorGenerator.generateColorForTag(newTag.getId());
                newTag.setColor(colors.getHexColor());
                newTag.setRgbColor(colors.getRgbaColor());
                // 更新颜色信息
                promptTagMapper.updateById(newTag);

                newTagIds.add(newTag.getId());
            }
        }

        // 2.2 合并现有标签ID和新创建的标签ID
        if (request.getTagIds() == null) {
            request.setTagIds(new ArrayList<>());
        }
        request.getTagIds().addAll(newTagIds);

        // 3. 插入模板
        PromptTemplateSquare template = new PromptTemplateSquare();
        template.setContent(request.getContent());
        template.setType(request.getType());
        template.setCreateTime(new Date());
        template.setUpdateTime(new Date());
        template.setDeleted(false);

        int rows = promptTemplateSquareMapper.insert(template);
        if (rows != 1) {
            throw new BaseException("500","创建模板失败");
        }

        // 4. 处理标签关联
        if (CollectionUtils.isNotEmpty(request.getTagIds())) {
            try {
                List<PromptRelationTag> relations = request.getTagIds().stream()
                        .map(tagId -> {
                            PromptRelationTag relation = new PromptRelationTag();
                            relation.setTemplateId(template.getId());
                            relation.setTagId(tagId);
                            relation.setCreateTime(new Date());
                            relation.setUpdateTime(new Date());
                            return relation;
                        })
                        .collect(Collectors.toList());
                promptRelationTagService.saveBatch(relations);
            } catch (DuplicateKeyException e) {
                throw new BaseException("500","标签关联关系重复");
            }
        }

        return template.getId();
    }
}